
import { Select, Switch } from "antd";
import React, { useEffect, useState } from "react";
import dayjs from 'dayjs';
import * as echarts from "echarts";
import { $eventBus, $ScientificNotation } from "../../../../../../common/utils";
import openDrawerImage from "../../../../../../assets/image/左内容展开@2x.png";
import closeDrawerImage from "../../../../../../assets/image/左内容收起@2x.png";
import lessModule from "./index.module.less";
import HomePage_DrawerComponent from "../../../../../../components/drawer";
import HomePage_HuashengbaSvgComponent from "../../../../../../components/svg/huaShengBa";
import HomePage_LaoNianSvgComponent from "../../../../../../components/svg/laoNian";
import HomePage_YuanBaoShanSvgComponent from "../../../../../../components/svg/yuanBaoShan";
import HomePage_LaoNianShoufeizhanSvgComponent from "../../../../../../components/svg/laoNianShouFeiZhan";
import HomePage_SuoGuHengDongSvgComponent from "../../../../../../components/svg/suoGuHengDong";
import HomePage_SuoGu1SvgComponent from "../../../../../../components/svg/suoGu1";
import HomePage_BaiMaZaSvgComponent from "../../../../../../components/svg/baiMaZa";
import HomePage_SuoGu2SvgComponent from "../../../../../../components/svg/suoGu2";
import HomePage_FuLong1SvgComponent from "../../../../../../components/svg/fuLong1";
import HomePage_FuLong2SvgComponent from "../../../../../../components/svg/fuLong2";
import HomePage_ChaiXiaLi1SvgComponent from "../../../../../../components/svg/chaiXiaLi1";
import HomePage_ChaiXiaLi2SvgComponent from "../../../../../../components/svg/chaiXiaLi2";
import HomePage_ChaiXiaLiHengDongSvgComponent from "../../../../../../components/svg/chaiXiaLiHengDong";
import HomePage_FuLongHengDongSvgComponent from "../../../../../../components/svg/fuLongHengDong";
import HomePage_MinZuCun1SvgComponent from "../../../../../../components/svg/minZuCun1";
import HomePage_MinZuCunHengDongSvgComponent from "../../../../../../components/svg/minZuCyunHengDong";
import HomePage_MinZuCun2SvgComponent from "../../../../../../components/svg/minZuCun2";
import HomePage_ZiYiLi1SvgComponent from "../../../../../../components/svg/ziYiLi1";
import HomePage_ZiYiLi2SvgComponent from "../../../../../../components/svg/ziYiLi2";
import { $Http } from "../../../../../../network";


// 主页-变电站能耗页面-实施功率页面-右边组件-下方组件
interface substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponentBottomComponentInterface {
    sourceData: object
}
const SubstationEnergyConsumptionPage_RealTimePowerPage_DrawerComponent_DrawerContentComponent_BottomComponent: React.FC<substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponentBottomComponentInterface> = (props) => {
    let echartsLine: echarts.ECharts
    const make_xList = () => {
        let xList: Array<string> = []
        let dateTime = new Date().getTime();
        for (let i = 0; i < 3600; i++) {
            i % 3 === 0 && xList.unshift(
                `${dayjs(dateTime - 1000 * i).format("HH:mm:ss")}`)
        }
        draw_echarts(xList)
    }
    const init_echarts = () => {
        echartsLine = echarts.init(document.getElementById("echartsLine") as HTMLElement)
    }
    const draw_echarts = (xList: Array<string>) => {
        const option = {
            title: {
                text: "功率（kW）",
                padding: [37, 0, 0, 21],
                textStyle: {
                    color: "#7A8F99",
                    fontSize: 12,
                    fontWeight: 400,
                },
            },
            tooltip: {
                trigger: "axis",
                backgroundColor: "rgba(13, 89, 128, 0.9)",
                borderColor: "#17A1E6",
                axisPointer: {
                    lineStyle: {
                        type: "solid",
                        color: "#17A1E6",
                    },
                },
                formatter(params: Array<object>) {
                    return `
                        <div class="${lessModule["substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponentBottomComponent-echartsLine__tooltip"]}">
                            <span>${params[0]["axisValueLabel"]}</span>
                            <div class="${lessModule["echartsLine-tooltip__row"]}">
                                <div class="${lessModule["tooltip-row__legend"]} ${lessModule["tooltip-row__legend0"]}"></div>
                                <div class="${lessModule["tooltip-row__seriesName"]}">${params[0]["seriesName"]}</div>
                                <div>${params[0]["data"]}</div>
                            </div>
                            <div class="${lessModule["echartsLine-tooltip__row"]}">
                                <div class="${lessModule["tooltip-row__legend"]} ${lessModule["tooltip-row__legend1"]}"></div>
                                <div class="${lessModule["tooltip-row__seriesName"]}">${params[1]["seriesName"]}</div>
                                <div>${params[1]["data"]}</div>
                            </div>
                            <div class="${lessModule["echartsLine-tooltip__row"]}">
                                <div class="${lessModule["tooltip-row__legend"]} ${lessModule["tooltip-row__legend2"]}"></div>
                                <div class="${lessModule["tooltip-row__seriesName"]}">${params[2]["seriesName"]}</div>
                                <div>${params[2]["data"]}</div>
                            </div>
                        </div>`;
                },
            },
            legend: {
                data: ["总进线有功", "变压器损耗", "负荷"],
                icon: "rect",
                itemWidth: 8,
                itemGap: 32,
                left: 16,
                itemHeight: 8,
                textStyle: {
                    color: "#8FB8CC",
                },
            },
            grid: {
                top: "70px",
                right: "19px",
                bottom: "0",
                left: "21px",
                containLabel: true,
            },

            xAxis: {
                type: "category",
                data: xList,
                axisLabel: {
                    align: "left",
                    color: "#7A8F99",
                    showMinLabel: true,
                    showMaxLabel: true,
                    margin: 10,
                    formatter: (() => {
                        return (item: object, idx: number) => {
                            const isLast = idx === xList.length - 1;
                            const label = isLast ? `{last|${item}}` : item;
                            return label;
                        };
                    })(),
                    interval: 1199,
                    rich: {
                        last: {
                            width: 0,
                            align: "right",
                        },
                    },
                },
                axisLine: {
                    lineStyle: {
                        color: "rgba(122, 143, 153, 0.5)",
                    },
                },
                axisTick: {
                    show: false,
                },
            },
            yAxis: {
                type: "value",
                splitLine: {
                    lineStyle: {
                        color: "rgba(122, 143, 153, 0.5)",
                    },
                },
                axisLabel: {
                    color: "#7A8F99",
                },
            },
            series: [
                {
                    name: "总进线有功",
                    type: "line",
                    data: props.sourceData?.["Inline_enery"],
                    color: "#5B8FF9",
                    symbol: "none",
                    smooth: true,
                    animation: false,
                },
                {
                    name: "变压器损耗",
                    type: "line",
                    data: props.sourceData?.["transformer_enery"],
                    color: "#5AD8A6",
                    symbol: "none",
                    smooth: true,
                    animation: false,
                },
                {
                    name: "负荷",
                    type: "line",
                    data: props.sourceData?.["Mainline_enery"],
                    color: "#5D7092",
                    symbol: "none",
                    smooth: true,
                    animation: false,
                },

            ],
        };

        echartsLine.setOption(option);
    }


    // 初始化
    useEffect(() => {
        init_echarts()
        make_xList()
        return () => {
            echartsLine?.dispose()
        }
    }, [props.sourceData])
    return (
        <div className={`${lessModule["substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent-main__panel"]} ${lessModule["substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent-main__substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponentBottomComponent"]}`}>
            <header className={`${lessModule["main-panel__header"]}`}>功率分配</header>
            <div className={`${lessModule["main-substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponentBottomComponent__echartsLine"]}`} id="echartsLine" ></div>
        </div>
    )
}




// 主页-变电所供电品质-抽屉内容组件
interface substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponentPropsInterface {
    siteName: string
    get_isDrawerClose: Function
    get_siteName: Function
    sourceData: object
}
const SubstationEnergyConsumptionPage_RealTimePowerPage_DrawerComponent_DrawerContentComponent: React.FC<substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponentPropsInterface> = (props) => {
    const powerList = [{ label: "总有功功率", key: "total_actpower" }, { label: "总无功功率", key: "" }, { label: "功率因数", key: "power_fac" }]
    const click_closeDrawer = () => {
        props.get_isDrawerClose()
    }
    const change_siteName = (value: string) => {
        props.get_siteName(value)
    }


    return (
        <div className={`${lessModule["homePageSubstationEnergyConsumptionPageRealTimePowerPage-substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent"]}`}>
            <img className={`${lessModule["homePageSubstationEnergyConsumptionPageRealTimePowerPage-substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent__closeDrawerImgae"]}`} src={closeDrawerImage} onClick={() => click_closeDrawer()} />
            <header className={`${lessModule["homePageSubstationEnergyConsumptionPageRealTimePowerPage-substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent__header"]}`}>
                <Select
                    className={`${lessModule["substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent-header__siteSelect"]}`}
                    popupClassName="header-siteSelect__selectDropdown"
                    optionLabelProp="labelProp"
                    value={props.siteName}
                    options={JSON.parse(sessionStorage.homePage_freewayList)}
                    fieldNames={{ value: "labelProp" }}
                    onChange={change_siteName}
                />
            </header>
            <main className={`${lessModule["homePageSubstationEnergyConsumptionPageRealTimePowerPage-substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent__main"]}`}>
                <div className={`${lessModule["substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent-main__panel"]} ${lessModule["substationEnergyConsumptionPageRealTimePowerPageDrawerComponentDrawerContentComponent-main__powerPanel"]}`}>
                    <header className={`${lessModule["main-panel__header"]}`}>10kV进线功率</header>
                    <main className={lessModule["main-powerPanel__main"]}>
                        {
                            powerList.map((item, idx) => {
                                return (
                                    <div key={"power" + idx} className={lessModule["powerPanel-main__card"]}>
                                        <div>{item["label"]}</div>
                                        <div className={lessModule["main-card__value"]}>{$ScientificNotation(props.sourceData?.[item["key"]])} {item["label"]!== "功率因数" && "KW"}</div>
                                    </div>
                                )
                            })
                        }
                    </main>
                </div>
                <SubstationEnergyConsumptionPage_RealTimePowerPage_DrawerComponent_DrawerContentComponent_BottomComponent sourceData={props.sourceData} />
            </main>

        </div>
    )
}

// 主页-变电站能耗页面-实时功率页面
const HomePage_SubstationEnergyConsumptionPage_RealTimePowerPage: React.FC = () => {
    let [isSwitch, setIsSwitch] = useState<boolean>(true)
    let [scaleValue, setScaleValue] = useState<number>(1)
    const [isDrawer, setIsDrawer] = useState<boolean>(true)
    const [isPrepareCloseDrawer, setIsPrepareCloseDrawer] = useState<boolean>(false)
    let [siteName, setSiteName] = useState<string>(`${JSON.parse(sessionStorage.homePage_freewayList)[0].label}/${JSON.parse(sessionStorage.homePage_freewayList)[0].options[0].label}`)
    let [sourceData, setSourceData] = useState<object>({})
    let [myInterval, setMyInterval] = useState<any>(null)
    const click_openDrawer = () => {
        setIsDrawer(true)
    }
    const get_isDrawerClose = () => {
        setIsPrepareCloseDrawer(true)
        setTimeout(() => {
            setIsDrawer(false)
            setIsPrepareCloseDrawer(false)
        }, 50);
    }
    const get_siteName = (value: string) => {
        siteName = value
        setSiteName(siteName)

        http_eneryConsumeEneryInformation()
    }
    const eventBus_on = () => {
        // 变电站能耗筛选数据
        $eventBus.addListener("eventBus_homePageSubstationEnergyConsumptionPageData", (res) => {
            isSwitch = res["isSwitch"]
            scaleValue = res["scaleValue"]
            setIsSwitch(isSwitch)
            setScaleValue(scaleValue)
        })
    }
    const eventBus_off = () => {
        // 变电站能耗筛选数据
        $eventBus.removeAllListeners("eventBus_homePageSubstationEnergyConsumptionPageData")
    }
    const http_eneryConsumeEneryInformation = () => {
        myInterval && clearInterval(myInterval)
        const func_execute = () => {
            $Http("eneryConsumeEneryInformation", { substation_name: siteName }).then((res) => {
                sourceData = res
                setSourceData(sourceData)
            })
        }
        func_execute()
        myInterval = setInterval(() => {
            func_execute()
        }, 3000)
        setMyInterval(myInterval)
    }
    useEffect(() => {
        // 销毁
        return () => {
            clearInterval(myInterval)
            setMyInterval(myInterval)
        }
    }, [sourceData])
    useEffect(() => {
        eventBus_on()
        http_eneryConsumeEneryInformation()
        return () => {
            eventBus_off()
        }
    }, [])
    return (
        <div className={`${lessModule["homePageSubstationEnergyConsumptionPageRealTimePowerPage"]}`}>
            <>
                {
                    siteName.split("/")[1] === "花生坝隧道" && <HomePage_HuashengbaSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "老碾隧道" && <HomePage_LaoNianSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "圆包山隧道" && <HomePage_YuanBaoShanSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "老碾收费站" && <HomePage_LaoNianShoufeizhanSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "白马匝道收费站" && <HomePage_BaiMaZaSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "索古修寨隧道洞内横洞变电所（进口）" && <HomePage_SuoGu1SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "索古修寨隧道洞内横洞变电所" && <HomePage_SuoGuHengDongSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "索古修寨隧道2#变电所（出口）" && <HomePage_SuoGu2SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "福隆隧道洞内横洞进口变电所" && <HomePage_FuLongHengDongSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "福隆隧道洞内1#横洞变电所" && <HomePage_FuLong1SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "福隆隧道 2#变电所" && <HomePage_FuLong2SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "柴呷哩隧道 1#变电所" && <HomePage_ChaiXiaLi1SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "柴呷哩隧道 横洞变电所" && <HomePage_ChaiXiaLiHengDongSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "柴呷哩隧道 2#变电所" && <HomePage_ChaiXiaLi2SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "民族村隧道 1#变电所" && <HomePage_MinZuCun1SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "民族村隧道 横洞变电所" && <HomePage_MinZuCunHengDongSvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "民族村隧道 2#变电所" && <HomePage_MinZuCun2SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "自一里隧道 1#箱变" && <HomePage_ZiYiLi1SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    siteName.split("/")[1] === "自一里隧道 2#变电所" && <HomePage_ZiYiLi2SvgComponent pageName="变电站能耗" scaleValue={scaleValue} isSwitch={isSwitch} sourceList={sourceData?.["real_enery"]} />
                }
            </>
            <>
                {
                    !isDrawer && <img className={`${lessModule["homePageSubstationEnergyConsumptionPageRealTimePowerPage-openDrawerImgae"]}`} src={openDrawerImage} onClick={() => click_openDrawer()} />
                }
            </>
            <>
                {
                    isDrawer && <HomePage_DrawerComponent top={65} isPrepareCloseDrawer={isPrepareCloseDrawer} get_isDrawerClose={get_isDrawerClose}
                        DrawerContentComponents={<SubstationEnergyConsumptionPage_RealTimePowerPage_DrawerComponent_DrawerContentComponent siteName={siteName} get_isDrawerClose={get_isDrawerClose} get_siteName={get_siteName} sourceData={sourceData} />} />
                }
            </>
        </div>
    )
}

export default HomePage_SubstationEnergyConsumptionPage_RealTimePowerPage


